<template>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: 'homepage' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
        <el-button type="primary" @click="showAppCate">添加分类</el-button>
        <!-- 表格 -->
        <el-table :data="catelist" row-key="cat_id" style="width: 100%;margin-top: 15px;" border stripe>
            <el-table-column width="50px" />
            <el-table-column prop="cat_id" label="分类编号" />
            <el-table-column prop="cat_name" label="分类名称" />
            <el-table-column label="分类等级">
                <template #default="scope">
                    <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
                    <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
                    <el-tag type="warning" v-else>三级</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="primary" icon="edit"
                        @click="handleEdit(scope.row.cat_id)">编辑</el-button>
                    <el-button size="small" type="danger" icon="delete"
                        @click="CateDelete(scope.row.cat_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="querInfo.pagenum" :page-sizes="[2, 5, 10, 12]" :page-size="querInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog v-model="catelogAdd" title="添加分类" width="450" @close="addcateClose()">
        <el-form :model="catefrom" :rules="addCateRules" ref="catefrom">
            <el-form-item label="分类名称" prop="cat_name">
                <el-input v-model="catefrom.cat_name" />
            </el-form-item>
            <el-form-item label="父级分类">
                <!-- options 绑定的数据源 -->
                <!-- props用来指定配置对象 -->
                <!-- v-model双向绑定选中的值 -->
                <el-cascader v-model="selestKeys" :options="PaentCateList" :props="cascaderProps" @change="handleChange"
                    clearable placeholder="请选择" ref="cascaderRef" style="width: 100%;">
                </el-cascader>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="catelogAdd = false">取消</el-button>
                <el-button type="primary" @click="addCate">提交</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog v-model="editDialog" title="修改分类" width="450" @close="CateClose()">
        <el-form :model="catefrom" :rules="addCateRules" ref="catefromtwo">
            <el-form-item label="分类名称" prop="cat_name">
                <el-input v-model="catefrom.cat_name" />
            </el-form-item>
        </el-form>
        <template #footer="">
            <div class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="addCate_two(this.editingId)">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ElMessage } from 'element-plus';
export default {
    data() {
        return {
            catelist: [],       //商品分类数据
            PaentCateList: [],   //父级分类数据
            selestKeys: [],         //父级分类选中的id
            total: 0,           //列表个数
            catelogAdd: false,    //控制添加分类对话框
            editDialog: false,     //控制编辑分类对话框
            catefrom: {          //添加分类表单的数据
                cat_pid: 0,     //分类父 ID
                cat_name: '',    //分类名称
                cat_level: 0    //分类层级
            },
            editingId: '',    //分类 ID
            cascaderProps: {    //指定级联选择器的配置对象
                value: 'cat_id',     //指定选项的值为选项对象的某个属性值
                label: 'cat_name',   //指定选项标签为选项对象的某个属性值
                children: 'children',   //指定选项的子选项为选项对象的某个属性值
                expandTrigger: 'hover',
                checkStrictly: true
            },
            querInfo: {
                type: 3,
                pagenum: 1,   //当前页码值
                pagesize: 5,   //每页显示多少条数据
            },
            //校验规则
            addCateRules: {
                cat_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ],
            }
        }
    },
    methods: {
        // 获取商品分类数据
        async getCateList() {
            const res = await this.$axios.get("categories", { params: this.querInfo })
            // console.log(res);
            this.catelist = res.data.data.result;
            this.total = res.data.data.total;
        },
        handleSizeChange(newSize) {       //监听pagesize改变的事件
            // console.log(newSize);
            this.querInfo.pagesize = newSize;
            this.getCateList()
        },
        handleCurrentChange(newSize) {    //监听页码值的事件
            // console.log(newSize);
            this.querInfo.pagenum = newSize;
            this.getCateList()
        },
        //控制添加分类的对话框
        showAppCate() {
            this.getPaentCateList()   //获取父级分类的数据列表
            this.catelogAdd = true   //显示添加分类对话框
        },
        //清空添加分类对话框内容
        addcateClose() {
            this.$refs.catefrom.resetFields()
            this.selestKeys = []
            this.catefrom.cat_level = 0
            this.catefrom.cat_pid = 0
        },
        //清空编辑分类对话框内容
        CateClose() {
            this.$refs.catefromtwo.resetFields()
        },
        //获取父级分类的数据列表
        async getPaentCateList() {
            const res = await this.$axios.get('categories', { type: 2 })
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: '获取成功',
                    type: 'success'
                })

                this.PaentCateList = res.data.data
                // console.log(this.PaentCateList);
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //父级分类框中选中发生的数据
        handleChange() {
            // console.log(this.selestKeys);
            if (this.selestKeys.length > 0) {
                //父级分类的id
                this.catefrom.cat_pid = this.selestKeys[
                    this.selestKeys.length - 1
                ]
                //为当前分类的等级赋值
                this.catefrom.cat_level = this.selestKeys.length
                return
            } else {
                //父级分类的id
                this.catefrom.cat_pid = 0
                //为当前分类的等级赋值
                this.catefrom.cat_level = 0
            }
            // 选中后关闭下拉面板
            this.$nextTick(() => {
                if (this.$refs.cascaderRef) {
                    // 尝试调用组件的方法来关闭
                    this.$refs.cascaderRef.handleClose?.();
                    // 或者直接操作组件的内部状态
                    this.$refs.cascaderRef.visible = false;
                }
            });
        },
        //添加分类对话框-确认
        addCate() {
            // console.log(this.catefrom);
            this.$refs.catefrom.validate(async valid => {     //验证表单通过才能提交
                if (!valid) return
                const res = await this.$axios.post('categories', this.catefrom)
                if (res.data.meta.status == 201) {
                    ElMessage({
                        message: '创建成功',
                        type: 'success'
                    })
                    this.getCateList()
                    this.catelogAdd = false;
                } else {
                    ElMessage.error(res.data.meta.msg)
                }
            })
        },
        //编辑按钮
        async handleEdit(id) {
            this.editingId = id
            // console.log(id);
            this.editDialog = true;
            const res = await this.$axios.get("categories/" + id)
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: "获取成功",
                    type: 'success'
                })
                this.catefrom = res.data.data
                // console.log(this.catefrom);
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //确认编辑按钮
        addCate_two(id) {
            // console.log(id);
            this.$refs.catefromtwo.validate(async valid => {           //验证表单通过才能提交
                if (!valid) return
                const res = await this.$axios.put("categories/" + id, { cat_name: this.catefrom.cat_name })
                // console.log(res);
                if (res.data.meta.status == 200) {
                    ElMessage({
                        message: '更新成功',
                        type: 'success'
                    })
                    this.editDialog = false;
                    this.getCateList()
                } else {
                    ElMessage.error(res.data.meta.msg)
                }
            })
        },
        //根据ID删除分类用户
        async CateDelete(id) {
            try {
                await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                const res = await this.$axios.delete("categories/" + id);
                console.log(res);
                if (res.data.meta.status == 200) {
                    this.getCateList();
                    this.$message({
                        message: "删除成功",
                        type: 'success'
                    })
                } else {
                    this.$message.error(res.meta.msg)
                }
            } catch (error) {
                if (error === 'cancel') {
                    this.$message.info('已取消删除')
                } else {
                    this.$message.error('删除失败')
                }
            }
        },

    },
    mounted() {    //挂载之后调用
        this.getCateList()
    }

}
</script>

<style scoped>
.el-table {
    margin-bottom: 15px;
}
</style>
